#include "kernel_operator.h"

constexpr int32_t BUFFER_NUM = 2;
class KernelL1lossgrad {
public:
    __aicore__ inline KernelL1lossgrad() {}
    __aicore__ inline void Init(GM_ADDR x, GM_ADDR y, GM_ADDR z, GM_ADDR u, uint32_t reduction,const L1lossgradTilingData &tiling_data) 
    {
        this->tiling=tiling_data;
        this->reduction=reduction;
        uint64_t coreNum = AscendC::GetBlockIdx();
        uint64_t globalBufferIndex = tiling.bigCoreDataNum * AscendC::GetBlockIdx();
        this->total = tiling.inputDataNum;
        this->ubPartDataNum = tiling.ubPartDataNum;
        if (tiling.tailBlockNum!=0) 
        {
          if (coreNum < tiling.tailBlockNum) 
          { 
            this->coreDataNum = tiling.bigCoreDataNum;
            this->tileNum = tiling.bigCoreLoopNum;
            this->tailDataNum = tiling.bigCoreTailDataNum;
          }
          else 
          { 
            this->coreDataNum = tiling.smallCoreDataNum;
            this->tileNum = tiling.smallCoreLoopNum;
            this->tailDataNum = tiling.smallCoreTailDataNum;
            globalBufferIndex -= (tiling.bigCoreDataNum - tiling.smallCoreDataNum) * (AscendC::GetBlockIdx() - tiling.tailBlockNum);
          }
        }
        else
        {
          this->coreDataNum = tiling.smallCoreDataNum;
          this->tileNum = tiling.smallCoreLoopNum;
          this->tailDataNum = tiling.smallCoreTailDataNum;
          globalBufferIndex = tiling.smallCoreDataNum * AscendC::GetBlockIdx();
        }
          
        xGm.SetGlobalBuffer((__gm__ float *)x + globalBufferIndex, this->coreDataNum);
        yGm.SetGlobalBuffer((__gm__ float *)y + globalBufferIndex, this->coreDataNum);
        uGm.SetGlobalBuffer((__gm__ float *)u + globalBufferIndex, this->coreDataNum);

        zGm.SetGlobalBuffer((__gm__ float *)z + globalBufferIndex, this->coreDataNum);

        pipe.InitBuffer(inQueueX, BUFFER_NUM, this->ubPartDataNum * sizeof(float));
        pipe.InitBuffer(inQueueY, BUFFER_NUM, this->ubPartDataNum * sizeof(float));
        pipe.InitBuffer(inQueueU, BUFFER_NUM, this->ubPartDataNum * sizeof(float));

        pipe.InitBuffer(outQueueZ, BUFFER_NUM, this->ubPartDataNum * sizeof(float));

        pipe.InitBuffer(tmpBuf0, this->ubPartDataNum * sizeof(float));
        pipe.InitBuffer(tmpBuf1, this->ubPartDataNum * sizeof(uint8_t));
        pipe.InitBuffer(tmpBuf2, this->ubPartDataNum * sizeof(float));
        pipe.InitBuffer(tmpBuf3, this->ubPartDataNum * sizeof(float));
    }
    
    __aicore__ inline void Process()
    {
        int32_t loopCount = this->tileNum;
        this->processDataNum = this->ubPartDataNum;
        for (int32_t i = 0; i < loopCount-1; i++) 
        {
            CopyIn(i);
            Compute(i);
            CopyOut(i);
        }
        this->processDataNum = this->tailDataNum;
        CopyIn(loopCount-1);
        Compute(loopCount-1);
        CopyOut(loopCount-1);
    }

private:
    __aicore__ inline void CopyIn(int32_t progress)
    {
        AscendC::LocalTensor<float> xLocal = inQueueX.AllocTensor<float>();
        AscendC::LocalTensor<float> yLocal = inQueueY.AllocTensor<float>();
        AscendC::LocalTensor<float> uLocal = inQueueU.AllocTensor<float>();

        AscendC::DataCopy(xLocal, xGm[progress * this->processDataNum], this->processDataNum);
        AscendC::DataCopy(yLocal, yGm[progress * this->processDataNum], this->processDataNum);
        AscendC::DataCopy(uLocal, uGm[progress * this->processDataNum], this->processDataNum);

        inQueueX.EnQue(xLocal);
        inQueueY.EnQue(yLocal);
        inQueueU.EnQue(uLocal);
    }
    __aicore__ inline void Compute(int32_t progress)
    {
        AscendC::LocalTensor<float> xLocal = inQueueX.DeQue<float>();
        AscendC::LocalTensor<float> yLocal = inQueueY.DeQue<float>();
        AscendC::LocalTensor<float> uLocal = inQueueU.DeQue<float>();
        AscendC::LocalTensor<float> zLocal = outQueueZ.AllocTensor<float>();

        AscendC::LocalTensor<float> tmpTensor0 = tmpBuf0.Get<float>();
        AscendC::Duplicate<float>(tmpTensor0, 1, this->processDataNum);
        AscendC::LocalTensor<uint8_t> tmpTensor1 = tmpBuf1.Get<uint8_t>();
        AscendC::LocalTensor<float> tmpTensor2 = tmpBuf2.Get<float>();
        AscendC::LocalTensor<float> tmpTensor3 = tmpBuf3.Get<float>();

      this->reduction=2;
      if(reduction == 0){//none
            
            AscendC::Sub(zLocal, xLocal, yLocal, this->processDataNum);
            AscendC::DumpTensor(zLocal, 1, 16);
            uint64_t mask0 = (this->processDataNum >= 64) ? 64 : this->processDataNum;
            int repeat0 =  (this->processDataNum + mask0 - 1) /mask0;
            AscendC::UnaryRepeatParams repeatParamss0 = { 1, 1, 8, 8 };
            AscendC::CompareScalar(tmpTensor1, zLocal, static_cast<float>(0), AscendC::CMPMODE::EQ, mask0, repeat0, repeatParamss0);
            AscendC::BinaryRepeatParams repeatParams0 = { 1, 1, 1, 8, 8, 8 };
            AscendC::Select(tmpTensor2, tmpTensor1, tmpTensor0, static_cast<float>(0), AscendC::SELMODE::VSEL_TENSOR_SCALAR_MODE, mask0, repeat0, repeatParams0);

            uint64_t mask1 = (this->processDataNum >= 64) ? 64 : this->processDataNum;
            int repeat1 = (this->processDataNum + mask1 - 1) /mask1;
            AscendC::UnaryRepeatParams repeatParamss1 = { 1, 1, 8, 8 };
            AscendC::CompareScalar(tmpTensor1, zLocal, static_cast<float>(0), AscendC::CMPMODE::GT, mask1, repeat1, repeatParamss1);
            AscendC::BinaryRepeatParams repeatParams1 = { 1, 1, 1, 8, 8, 8 };
            AscendC::Select(tmpTensor3, tmpTensor1, tmpTensor0, static_cast<float>(0), AscendC::SELMODE::VSEL_TENSOR_SCALAR_MODE, mask1, repeat1, repeatParams1);
            AscendC::Add(tmpTensor2, tmpTensor3, tmpTensor2, this->processDataNum);

            uint64_t mask2 = (this->processDataNum >= 64) ? 64 : this->processDataNum;
            int repeat2 = (this->processDataNum + mask2 - 1) /mask2;
            AscendC::UnaryRepeatParams repeatParamss2 = { 1, 1, 8, 8 };
            AscendC::CompareScalar(tmpTensor1, zLocal, static_cast<float>(0), AscendC::CMPMODE::LE, mask2, repeat2, repeatParamss2);
            AscendC::BinaryRepeatParams repeatParams2 = { 1, 1, 1, 8, 8, 8 };
            AscendC::Select(tmpTensor3, tmpTensor1, tmpTensor0, static_cast<float>(0), AscendC::SELMODE::VSEL_TENSOR_SCALAR_MODE, mask2, repeat2, repeatParams2);
            AscendC::Muls(tmpTensor3, tmpTensor3, static_cast<float>(-1.0), this->processDataNum);
            AscendC::Add(zLocal, tmpTensor3, tmpTensor2, this->processDataNum);
            AscendC::DumpTensor(zLocal, 2, 16);
            AscendC::Mul(zLocal, zLocal, uLocal, this->processDataNum);

        }else if(reduction == 1){//sum
            AscendC::Sub(zLocal, xLocal, yLocal, this->processDataNum);
            AscendC::DumpTensor(zLocal, 1, 16);
            uint64_t mask0 = (this->processDataNum >= 64) ? 64 : this->processDataNum;
            int repeat0 =  (this->processDataNum + mask0 - 1) /mask0;
            AscendC::UnaryRepeatParams repeatParamss0 = { 1, 1, 8, 8 };
            AscendC::CompareScalar(tmpTensor1, zLocal, static_cast<float>(0), AscendC::CMPMODE::EQ, mask0, repeat0, repeatParamss0);
            AscendC::BinaryRepeatParams repeatParams0 = { 1, 1, 1, 8, 8, 8 };
            AscendC::Select(tmpTensor2, tmpTensor1, tmpTensor0, static_cast<float>(0), AscendC::SELMODE::VSEL_TENSOR_SCALAR_MODE, mask0, repeat0, repeatParams0);

            uint64_t mask1 = (this->processDataNum >= 64) ? 64 : this->processDataNum;
            int repeat1 = (this->processDataNum + mask1 - 1) /mask1;
            AscendC::UnaryRepeatParams repeatParamss1 = { 1, 1, 8, 8 };
            AscendC::CompareScalar(tmpTensor1, zLocal, static_cast<float>(0), AscendC::CMPMODE::GT, mask1, repeat1, repeatParamss1);
            AscendC::BinaryRepeatParams repeatParams1 = { 1, 1, 1, 8, 8, 8 };
            AscendC::Select(tmpTensor3, tmpTensor1, tmpTensor0, static_cast<float>(0), AscendC::SELMODE::VSEL_TENSOR_SCALAR_MODE, mask1, repeat1, repeatParams1);
            AscendC::Add(tmpTensor2, tmpTensor3, tmpTensor2, this->processDataNum);

            uint64_t mask2 = (this->processDataNum >= 64) ? 64 : this->processDataNum;
            int repeat2 = (this->processDataNum + mask2 - 1) /mask2;
            AscendC::UnaryRepeatParams repeatParamss2 = { 1, 1, 8, 8 };
            AscendC::CompareScalar(tmpTensor1, zLocal, static_cast<float>(0), AscendC::CMPMODE::LE, mask2, repeat2, repeatParamss2);
            AscendC::BinaryRepeatParams repeatParams2 = { 1, 1, 1, 8, 8, 8 };
            AscendC::Select(tmpTensor3, tmpTensor1, tmpTensor0, static_cast<float>(0), AscendC::SELMODE::VSEL_TENSOR_SCALAR_MODE, mask2, repeat2, repeatParams2);
            AscendC::Muls(tmpTensor3, tmpTensor3, static_cast<float>(-1.0), this->processDataNum);
            AscendC::Add(zLocal, tmpTensor3, tmpTensor2, this->processDataNum);
            AscendC::DumpTensor(zLocal, 2, 16);
            AscendC::Duplicate<float>(uLocal, static_cast<float>(1.0), this->processDataNum);
            AscendC::Mul(zLocal, zLocal, uLocal, this->processDataNum);

        }else if(reduction == 2) {//mean
            AscendC::Sub(zLocal, xLocal, yLocal, this->processDataNum);
            AscendC::DumpTensor(zLocal, 1, 16);
            uint64_t mask0 = (this->processDataNum >= 64) ? 64 : this->processDataNum;
            int repeat0 =  (this->processDataNum + mask0 - 1) /mask0;
            AscendC::UnaryRepeatParams repeatParamss0 = { 1, 1, 8, 8 };
            AscendC::CompareScalar(tmpTensor1, zLocal, static_cast<float>(0), AscendC::CMPMODE::EQ, mask0, repeat0, repeatParamss0);
            AscendC::BinaryRepeatParams repeatParams0 = { 1, 1, 1, 8, 8, 8 };
            AscendC::Select(tmpTensor2, tmpTensor1, tmpTensor0, static_cast<float>(0), AscendC::SELMODE::VSEL_TENSOR_SCALAR_MODE, mask0, repeat0, repeatParams0);

            uint64_t mask1 = (this->processDataNum >= 64) ? 64 : this->processDataNum;
            int repeat1 = (this->processDataNum + mask1 - 1) /mask1;
            AscendC::UnaryRepeatParams repeatParamss1 = { 1, 1, 8, 8 };
            AscendC::CompareScalar(tmpTensor1, zLocal, static_cast<float>(0), AscendC::CMPMODE::GT, mask1, repeat1, repeatParamss1);
            AscendC::BinaryRepeatParams repeatParams1 = { 1, 1, 1, 8, 8, 8 };
            AscendC::Select(tmpTensor3, tmpTensor1, tmpTensor0, static_cast<float>(0), AscendC::SELMODE::VSEL_TENSOR_SCALAR_MODE, mask1, repeat1, repeatParams1);
            AscendC::Add(tmpTensor2, tmpTensor3, tmpTensor2, this->processDataNum);

            uint64_t mask2 = (this->processDataNum >= 64) ? 64 : this->processDataNum;
            int repeat2 = (this->processDataNum + mask2 - 1) /mask2;
            AscendC::UnaryRepeatParams repeatParamss2 = { 1, 1, 8, 8 };
            AscendC::CompareScalar(tmpTensor1, zLocal, static_cast<float>(0), AscendC::CMPMODE::LE, mask2, repeat2, repeatParamss2);
            AscendC::BinaryRepeatParams repeatParams2 = { 1, 1, 1, 8, 8, 8 };
            AscendC::Select(tmpTensor3, tmpTensor1, tmpTensor0, static_cast<float>(0), AscendC::SELMODE::VSEL_TENSOR_SCALAR_MODE, mask2, repeat2, repeatParams2);
            AscendC::Muls(tmpTensor3, tmpTensor3, static_cast<float>(-1.0), this->processDataNum);
            AscendC::Add(zLocal, tmpTensor3, tmpTensor2, this->processDataNum);
            AscendC::DumpTensor(zLocal, 2, 16);

            AscendC::Duplicate<float>(uLocal, 1.0f / static_cast<float>(this->total), this->processDataNum);
            AscendC::Mul(zLocal, zLocal, uLocal, this->processDataNum);
            //AscendC::Muls(zLocal, zLocal,  1.0f / static_cast<float>(this->total), this->processDataNum);
        }

        outQueueZ.EnQue<float>(zLocal);
        inQueueX.FreeTensor(xLocal);
        inQueueY.FreeTensor(yLocal);
        inQueueX.FreeTensor(uLocal);
    }
    
    __aicore__ inline void CopyOut(int32_t progress)
    {
        AscendC::LocalTensor<float> zLocal = outQueueZ.DeQue<float>();
        AscendC::DataCopy(zGm[progress * this->ubPartDataNum], zLocal, this->processDataNum);
        outQueueZ.FreeTensor(zLocal);
    }
private:
    AscendC::TPipe pipe;
    AscendC::TQue<AscendC::TPosition::VECIN, BUFFER_NUM> inQueueX, inQueueY,inQueueU;
    AscendC::TQue<AscendC::TPosition::VECOUT, BUFFER_NUM> outQueueZ;
    AscendC::TBuf<AscendC::TPosition::VECCALC> tmpBuf0;
    AscendC::TBuf<AscendC::TPosition::VECCALC> tmpBuf1;
    AscendC::TBuf<AscendC::TPosition::VECCALC> tmpBuf2;
    AscendC::TBuf<AscendC::TPosition::VECCALC> tmpBuf3;
    AscendC::GlobalTensor<float> xGm;
    AscendC::GlobalTensor<float> yGm;
    AscendC::GlobalTensor<float> zGm;
    AscendC::GlobalTensor<float> uGm;
    uint32_t reduction;
    float sum;
    uint64_t coreDataNum;
    uint64_t tileNum;
    uint64_t ubPartDataNum;
    uint64_t tailDataNum;
    uint64_t processDataNum;
    int32_t total;
    L1lossgradTilingData tiling;
};

extern "C" __global__ __aicore__ void l1lossgrad_custom(GM_ADDR x, GM_ADDR y, GM_ADDR z,GM_ADDR u, GM_ADDR workspace, GM_ADDR tiling)
{
    GET_TILING_DATA(tiling_data, tiling);
    uint32_t reduction = 0;
    KernelL1lossgrad op;
    op.Init(x, y, z, u, reduction, tiling_data);
    op.Process();
}

